package com.maixy.studyonlineapi.redis.template;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis操作鸡肋
 * Created by jason on 17-3-27.
 */
@Component
public class BaseRedisTemplate {

    public final Logger logger = LoggerFactory.getLogger(BaseRedisTemplate.class);

    @Resource(name = "redisTemplate")
    protected RedisTemplate<String, String> redisTemplate;

    public boolean exists(String key) {
        Boolean result = redisTemplate.hasKey(key);
        return result == null ? false : result;
    }

    public void del(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            logger.error("redisTemplate.delete error key={}", key, e);
        }
    }

    public void delAll(Set<String> list){
        redisTemplate.delete(list);
    }

    public void delAll(List<String> list){
        redisTemplate.delete(list);
    }

    public void expire(String key, long timeout) {
        redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }

    public void persist(String key) {
        redisTemplate.persist(key);
    }

    public void expire(String key, long timeout, TimeUnit timeUnit) {
        redisTemplate.expire(key, timeout, timeUnit);
    }

    public long ttl(String key) {
        return redisTemplate.getExpire(key);
    }

    public RedisTemplate<String, String> getRedisTemplate() {
        return this.redisTemplate;
    }
}
